package wsz.mapper;

import wsz.sqlSession.SqlSession;

import java.util.HashMap;
import java.util.Map;

/**
 * mapper注册
 * @author wsz
 * @date 2021/10/9 10:05
 **/
public class MapperRegistry {

    /**
     * mapper注册容器
     * key: 限定名
     * value: 代理的工厂类
     */
    private Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap();

    public MapperRegistry() {
    }

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        MapperProxyFactory proxyFactory = this.knownMappers.get(type);
        if (proxyFactory == null) {
            throw  new RuntimeException("type " + type + " cannot found");
        }

        return (T) proxyFactory.newInstance(sqlSession);
    }

    public <T> boolean hasMapper(Class<T> type) {
        return this.knownMappers.containsKey(type);
    }

    public <T> void addMapper(Class<T> type) {
        if (type.isInterface()) {
            // 不能重复注册
            if (this.hasMapper(type)) {
                throw new RuntimeException("Type " + type + " is already known to the MapperRegistry.");
            }

            this.knownMappers.put(type, new MapperProxyFactory(type));
        }

    }
}
